package com.analysis.controller;

import com.analysis.dto.ApiResponse;
import com.analysis.dto.PageResponse;
import com.analysis.dto.QuestionAddRequest;
import com.analysis.dto.QuestionPageRequest;
import com.analysis.entity.Project;
import com.analysis.entity.Question;
import com.analysis.entity.User;
import com.analysis.enums.RequireLogin;
import com.analysis.service.ProjectService;
import com.analysis.service.QuestionService;
import com.analysis.utils.QuestionExcelExportUtils;
import com.analysis.utils.UserUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 问题控制器
 */
@RestController
@RequestMapping("/api/questions")
@CrossOrigin(origins = "*")
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private ProjectService projectService;

    /**
     * POST方式多条件分页查询问题（支持复杂查询条件）
     */
    @PostMapping("/page")
    @RequireLogin
    public ApiResponse<PageResponse<Question>> searchQuestionsByPage(@RequestBody QuestionPageRequest request, HttpServletRequest httpRequest) {
        try {
            // 设置项目ID
            request.setProjectId(getProjectId(httpRequest));

            // 参数验证
            if (request.getPageNum() < 1) {
                request.setPageNum(1);
            }
            if (request.getPageSize() < 1) {
                request.setPageSize(10);
            }

            // 执行分页查询
            PageResponse<Question> pageResponse = questionService.getQuestionsByPageWithConditions(request);
            return ApiResponse.success(pageResponse);
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("搜索分页查询问题时发生错误: " + e.getMessage());
        }
    }

    /**
     * 创建问题
     */
    @PostMapping("/add")
    @RequireLogin
    public ApiResponse<Question> createQuestion(@RequestBody Question question, HttpServletRequest request) {
        try {
            // 设置项目
            initProjectId(question, request);

            int result = questionService.createQuestion(question);
            if (result > 0) {
                return ApiResponse.success(question);
            } else {
                return ApiResponse.error("问题已存在，无法重复创建");
            }
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("创建问题时发生错误: " + e.getMessage());
        }
    }

    /**
     * 批量创建问题
     */
    @PostMapping("/batchAdd")
    @RequireLogin
    public ApiResponse<Question> batchAddQuestion(@RequestBody QuestionAddRequest request, HttpServletRequest httpServletRequest) {
        try {
            if (request.getQuestions() == null) {
                return ApiResponse.error("问题不存在");
            }
            Long companyId = UserUtils.getCurrentUserOrThrow(httpServletRequest).getCompanyId();
            Project project = projectService.getSelectedByCompanyId(companyId);
            if (project == null) {
                throw new IllegalArgumentException("项目不存在或无权限操作");
            }
             questionService.batchAddQuestion(project,request.getQuestions());
            return ApiResponse.success();
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("创建问题时发生错误: " + e.getMessage());
        }
    }

    /**
     * 根据ID删除问题
     */
    @PostMapping("/delete")
    @RequireLogin
    public ApiResponse<String> deleteQuestion(Long id, HttpServletRequest request) {
        try {
            Long projectId = getProjectId(request);
            Question question = questionService.getQuestionById(id);
            if (question == null || !question.getProjectId().equals(projectId)) {
                return ApiResponse.error("问题不存在或无权限操作");
            }
            int result = questionService.deleteQuestion(id);
            if (result > 0) {
                return ApiResponse.success("问题删除成功");
            } else {
                return ApiResponse.error("问题不存在或删除失败");
            }
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("删除问题时发生错误: " + e.getMessage());
        }
    }

    /**
     * 更新问题信息
     */
    @PostMapping("/update")
    @RequireLogin
    public ApiResponse<Question> updateQuestion(@RequestBody Question question, HttpServletRequest request) {
        try {
            initProjectId(question, request);
            Question exist = questionService.getQuestionById(question.getId());
            if (exist == null || !exist.getProjectId().equals(question.getProjectId())) {
                return ApiResponse.error("问题不存在或无权限操作");
            }
            int result = questionService.updateQuestion(question);
            if (result > 0) {
                return ApiResponse.success();
            } else {
                return ApiResponse.error("问题不存在或更新失败");
            }
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("更新问题时发生错误: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询问题
     */
    @GetMapping("/get")
    @RequireLogin
    public ApiResponse<Question> getQuestionById(Long id, HttpServletRequest request) {
        try {
            Long projectId = getProjectId(request);
            Question question = questionService.getQuestionById(id);
            if (question != null && question.getProjectId().equals(projectId)) {
                return ApiResponse.success(question);
            } else {
                return ApiResponse.error("问题不存在");
            }
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("查询问题时发生错误: " + e.getMessage());
        }
    }

    /**
     * 导出问题数据到Excel
     *
     * @param request            查询请求参数
     * @param httpServletRequest HTTP请求对象
     * @return Excel文件响应
     */
    @PostMapping("/export/excel")
    @RequireLogin
    public ResponseEntity<byte[]> exportQuestionsToExcel(@RequestBody QuestionPageRequest request,
                                                         HttpServletRequest httpServletRequest) {
        try {
            // 获取当前用户
            User currentUser = UserUtils.getCurrentUserOrThrow(httpServletRequest);
            // 获取当前选中的项目（按公司）
            Project selectedProject = projectService.getSelectedByCompanyId(currentUser.getCompanyId());
            if (selectedProject == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body("请先选择一个项目".getBytes());
            }
            // 设置项目ID，确保只能导出当前项目的数据
            request.setProjectId(selectedProject.getId());

            // 导出Excel
            byte[] excelBytes = questionService.exportQuestionsToExcel(request);

            if (excelBytes.length == 0) {
                return ResponseEntity.status(HttpStatus.NO_CONTENT)
                        .body("No data to export".getBytes());
            }

            // 生成文件名
            String fileName = QuestionExcelExportUtils.generateFileName("questions_data");

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            // 正确处理中文文件名编码
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8)
                    .replaceAll("\\+", "%20");
            headers.set("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);
            headers.setContentLength(excelBytes.length);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelBytes);

        } catch (IllegalStateException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(("User not logged in or session expired: " + e.getMessage()).getBytes());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("Excel export failed: " + e.getMessage()).getBytes());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("Error exporting questions data: " + e.getMessage()).getBytes());
        }
    }

    /**
     * GET方式导出问题数据到Excel（支持URL参数）
     *
     * @param request            查询请求参数
     * @param httpServletRequest HTTP请求对象
     * @return Excel文件响应
     */
    @GetMapping("/export/excel")
//    @RequireLogin
    public ResponseEntity<byte[]> exportQuestionsToExcelGet(QuestionPageRequest request,
                                                            HttpServletRequest httpServletRequest) {
        try {

            // 导出Excel
            byte[] excelBytes = questionService.exportQuestionsToExcel(request);

            if (excelBytes.length == 0) {
                return ResponseEntity.status(HttpStatus.NO_CONTENT)
                        .body("No data to export".getBytes());
            }

            // 生成文件名
            String fileName = QuestionExcelExportUtils.generateFileName("questions_data");

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            // 正确处理中文文件名编码
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8)
                    .replaceAll("\\+", "%20");
            headers.set("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);
            headers.setContentLength(excelBytes.length);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelBytes);

        } catch (IllegalStateException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(("User not logged in or session expired: " + e.getMessage()).getBytes());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("Excel export failed: " + e.getMessage()).getBytes());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("Error exporting questions data: " + e.getMessage()).getBytes());
        }
    }

    public Long getProjectId(HttpServletRequest request) {
        Long companyId = UserUtils.getCurrentUserOrThrow(request).getCompanyId();
        Project project = projectService.getSelectedByCompanyId(companyId);
        if (project == null) {
            throw new IllegalArgumentException("项目不存在或无权限操作");
        }
        return project.getId();
    }

    public void initProjectId(Question question, HttpServletRequest request) {
        Long companyId = UserUtils.getCurrentUserOrThrow(request).getCompanyId();
        Project project = projectService.getSelectedByCompanyId(companyId);
        if (project == null) {
            throw new IllegalArgumentException("项目不存在或无权限操作");
        }
        question.setProjectId(project.getId());
        question.setCompanyId(project.getCompanyId());
    }

}
